package net.frcdb.eventmanager;

import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.swing.AbstractListModel;
import javax.swing.DefaultListModel;
import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.LayoutStyle;
import javax.swing.ListModel;
import javax.swing.WindowConstants;
import net.frcdb.eventmanager.api.Event;
import net.frcdb.eventmanager.util.Dialog;
import org.apache.commons.lang.StringUtils;

/**
 *
 * @author tim
 */
public class SearchDialog extends javax.swing.JDialog {

	private List<Node> sorted;
	
	private Event selection;
	
	/**
	 * Creates new form SearchDialog
	 */
	public SearchDialog(Frame parent, List<Event> candidates, Event target) {
		super(parent, true);
		
		setTitle("Event Search");
		
		sorted = new ArrayList<Node>();
		for (Event candidate : candidates) {
			Node n = new Node();
			n.candidate = candidate;
			n.distance = StringUtils.getLevenshteinDistance(
					candidate.getName(), target.getName());
			sorted.add(n);
		}
		Collections.sort(sorted);
		
		initComponents();
		
		list.setSelectedIndex(0);
		list.requestFocusInWindow();
		
		pack();
		setLocationRelativeTo(parent);
		setVisible(true);
	}

	public Event getSelection() {
		return selection;
	}
	
	/**
	 * This method is called from within the constructor to initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is always
	 * regenerated by the Form Editor.
	 */
	@SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        listScroll = new JScrollPane();
        list = new JList();
        selectButton = new JButton();

        setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);

        list.setModel(listModel);
        list.addKeyListener(new KeyAdapter() {
            public void keyPressed(KeyEvent evt) {
                listKeyPressed(evt);
            }
        });
        listScroll.setViewportView(list);

        selectButton.setText("Select");
        selectButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                selectButtonActionPerformed(evt);
            }
        });

        GroupLayout layout = new GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                    .addComponent(listScroll, GroupLayout.Alignment.TRAILING, GroupLayout.DEFAULT_SIZE, 408, Short.MAX_VALUE)
                    .addComponent(selectButton, GroupLayout.Alignment.TRAILING, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(listScroll, GroupLayout.DEFAULT_SIZE, 370, Short.MAX_VALUE)
                .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(selectButton, GroupLayout.PREFERRED_SIZE, 27, GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void selectButtonActionPerformed(ActionEvent evt) {//GEN-FIRST:event_selectButtonActionPerformed
        Node n = (Node) list.getSelectedValue();
		if (n == null) {
			Dialog.error(this, "No value selected!");
			return;
		}
		
		selection = n.candidate;
		dispose();
    }//GEN-LAST:event_selectButtonActionPerformed

    private void listKeyPressed(KeyEvent evt) {//GEN-FIRST:event_listKeyPressed
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
			selectButtonActionPerformed(null);
		}
    }//GEN-LAST:event_listKeyPressed

	private class Node implements Comparable<Node> {
		
		private int distance;
		private Event candidate;

		public int compareTo(Node o) {
			return distance - o.distance;
		}

		@Override
		public String toString() {
			return candidate.getName() + " (" + candidate.getShortName() + ")";
		}

	}
	
	private AbstractListModel listModel = new AbstractListModel() {

		public int getSize() {
			return sorted.size();
		}

		public Object getElementAt(int index) {
			return sorted.get(index);
		}
		
	};
	
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private JList list;
    private JScrollPane listScroll;
    private JButton selectButton;
    // End of variables declaration//GEN-END:variables
}
